// edit-baoming.js
const http = require('../../../utils/http.js');
const tools = require('../../../utils/tools.js');

Page({
  data: {
    baoming_candidate_info: {
      id_number: '',
      vocational_college_id: null,
      vocational_major_id: null,
      candidate_type_id: null,
      exam_center_city_id: null,
      exam_major_id: null,
      volunteer_college_id: null,
      volunteer_major_id: null,
      // is_certificate_issued: '否'
    },
    vocationalColleges: [],
    vocationalCollegeMajors: [],
    candidateTypes: [],
    examCenters: [],
    examMajors: [],
    volunteerColleges: [],
    volunteerCollegeMajors: [],

    vocationalCollegeIndex: null,
    vocationalCollegeMajorIndex: null,
    candidateTypeIndex: null,
    examCenterIndex: null,
    examMajorIndex: null,
    volunteerCollegeIndex: null,
    volunteerCollegeMajorIndex: null,

    recordedText:null,
    recording: false,  // 用于标记当前是否正在录音
    isPaused: false,   // 用于标记录音是否处于暂停状态
    recordFilePath: '',  // 用于保存录音文件的临时路径
    editableContent: '', // 用于保存识别后文本内容的初始化
    buttonText: '开始录音', // 新增按钮文本控制变量
  },

  onLoad() {
    this.loadOptions().then(() => {
      this.loadStoredInfo();
    }).catch(err => {
      console.error('加载数据失败:', err);
    });
  },

  // 加载数据表
  async loadOptions() {
    try {
      const promises = [
        tools.fetchOptions('/vocationalcollege/list', 'vocationalColleges',this),
        tools.fetchOptions('/candidateType/list', 'candidateTypes',this),
        tools.fetchOptions3('/city/list', 'examCenters',this),
        tools.fetchOptions('/major/list', 'examMajors',this),
        tools.fetchOptions('/volunteercollege/list', 'volunteerColleges',this)
      ];
      await Promise.all(promises);
      console.log('所有数据加载完成');
      this.loadStoredInfo();
    } catch (err) {
      console.error('加载选项失败:', err);
    }
  },
  
  // 加载本地数据
  async loadStoredInfo() {
    const storedInfo = wx.getStorageSync('baoming_candidate_info');
    if (storedInfo) {
      this.setData({
        baoming_candidate_info: storedInfo
      });
      // 确保志愿和专科专业数据正确加载后再设置下标
      await this.loadvvMajors();
      this.updateIndexes(storedInfo);
    }
  },

  // 更新专业
  async loadvvMajors() {
    const fields = ['volunteerCollege', 'vocationalCollege'];
    for (const element of fields) {
        const element2 = element === 'vocationalCollege' ? 'vocational_college' : 'volunteer_college' 
      const college_id = `${element2}_id`;
      const id = this.data.baoming_candidate_info[college_id];
      if (id) {
        const endpoint = element === 'vocationalCollege' ? `/vocationalmajor/listByCollegeId?collegeId=${id}` : `/volunteermajor/listByCollegeId?collegeId=${id}`;
        await tools.fetchOptions(endpoint, `${element}Majors`,this);
      }
    }
  },
  
  // 更新下标
  updateIndexes(storedInfo) {
    const indexes = {
      vocationalCollegeIndex: tools.findIndexById(this.data.vocationalColleges, storedInfo.vocational_college_id),
      vocationalCollegeMajorIndex: tools.findIndexById(this.data.vocationalCollegeMajors, storedInfo.vocational_major_id),
      candidateTypeIndex: tools.findIndexById(this.data.candidateTypes, storedInfo.candidate_type_id),
      examCenterIndex: tools.findIndexById(this.data.examCenters, storedInfo.exam_center_city_id),
      examMajorIndex: tools.findIndexById(this.data.examMajors, storedInfo.exam_major_id),
      volunteerCollegeIndex: tools.findIndexById(this.data.volunteerColleges, storedInfo.volunteer_college_id),
      volunteerCollegeMajorIndex: tools.findIndexById(this.data.volunteerCollegeMajors, storedInfo.volunteer_major_id)
    };
  
    // 更新下标
    for (const key in indexes) {
      if (indexes[key] !== null) {
        console.log(`${key}: ${indexes[key]}`);
        this.setData({ [key]: indexes[key] });
      } else {
        console.warn(`未找到 ${key} 的索引，可能是数据未加载或 id 不匹配`);
      }
    }
  },

  // 选择后的逻辑
  handlePickerChange(e) {
    const { field } = e.currentTarget.dataset;
    const index = e.detail.value;
    const id = this.data[`${field}s`][index].id;
  
    if (!id) {
      console.error(`选项数据中未找到有效的 id，field: ${field}, index: ${index}`);
      return;
    }

    const mapField ={
        vocationalCollege : 'vocational_college_id',
        vocationalCollegeMajor: 'vocational_major_id',
        candidateType: 'candidate_type_id',
        examCenter: 'exam_center_city_id',
        examMajor:'exam_major_id',
        volunteerCollege : 'volunteer_college_id',
        volunteerCollegeMajor: 'volunteer_major_id',
    }
  
    this.setData({
      [`baoming_candidate_info.${mapField[field]}`]: id,
      [`${field}Index`]: index
    });
  
    // 加载志愿或专科专业选项
    if (field === 'volunteerCollege' || field === 'vocationalCollege') {
      const endpoint = field === 'vocationalCollege' 
        ? `/vocationalmajor/listByCollegeId?collegeId=${id}` 
        : `/volunteermajor/listByCollegeId?collegeId=${id}`;
      tools.fetchOptions(endpoint, `${field}Majors`,this).then(() => {
        console.log(`${field}Majors 数据加载成功`);
      }).catch(err => {
        console.error(`加载 ${field}Majors 数据失败:`, err);
      });
    }
  },  

  // 输入的处理逻辑
  handleInput(e) {
    const { field } = e.currentTarget.dataset;
    this.setData({
      [`baoming_candidate_info.${field}`]: e.detail.value
    });
  },

  // 下一页的处理逻辑
  handleSubmit() {
    // 检查字段是否发生改变
    const fieldsToCheck = [
      'candidate_category_code',  // 考生类别代码
      'candidate_type_code',      // 考生类型代码
      'registration_site_code',   // 报名点代码
      'graduation_school_code',   // 毕业院校代码
      'schooling_length',         // 学制
      'mailing_address',          // 通信地址
      'postal_code',              // 邮政编码
      'special_skills',           // 特长
      'work_school_code',         // 工作单位或学校代码
      'junior_position'           // 初级职务
    ];
    if(tools.checkDataChanged(this.data.baoming_candidate_info, wx.getStorageSync('baoming_candidate_info'),fieldsToCheck)){
      http.post('/candidate/updateRegistrationInfo', this.data.baoming_candidate_info).then(res => {
        if (res.statusCode === 200) {
          wx.setStorageSync('baoming_candidate_info', this.data.baoming_candidate_info);
          wx.showToast({ title: '报考信息更新成功', duration: 2000 });
          wx.navigateTo({ url: '/pages/zhuanshengben/edit-post/edit-post' });
        }
      }).catch(err => {
        console.error('报考信息更新失败:', err);
        wx.showToast({ title: '报考信息更新失败', icon: 'none' });
      });
    }else{
      wx.navigateTo({ url: '/pages/zhuanshengben/edit-post/edit-post' });
    }
  },

  handleNavigateBack() {
    wx.navigateTo({ url: '/pages/edit-base/edit-base' });
  },

  // 通过name查找对应id
  findIdByName(options, name){
      if(!options || !Array.isArray(options)) {
          console.error('选项数据无效或不是数组',options);
          return null;
      }
      let item = null;
      item = options.find(option => option.name == name) ? options.find(option => option.name == name) : options.find(option => option.cityName == name)
      
      return item ? item.id : null;
  },
  // 根据返回的数据，更新对应的数据包含id和对应index
  // 传入数据是包含各个数据字段的字典
  async updateIdAndIndex(dataFields){
      // 传入字典key和id的映射表
      const fields = {
        vocational_college: "vocational_college_id",
        volunteer_college: "volunteer_college_id",
        candidate_type: "candidate_type_id",
        exam_center_city: "exam_center_city_id",
        exam_major: "exam_major_id",
        // is_certificate_issued: "is_certificate_issued"
      }
      const majorFields = {
        vocational_major: "vocational_major_id",
        volunteer_major: "volunteer_major_id",
      }
      // 传入字典和数组的映射表
      const arrayFields = {
        vocational_college: 'vocationalColleges',
        vocational_major: 'vocationalCollegeMajors',
        candidate_type: 'candidateTypes',
        exam_center_city: 'examCenters',
        exam_major: 'examMajors',
        volunteer_college: 'volunteerColleges',
        volunteer_major: 'volunteerCollegeMajors'
      }
      // 遍历fields字典，获取对应值并赋值id
      Object.entries(fields).forEach(([key,value]) =>{
        console.log(dataFields[key])
        if(!dataFields[key].includes("未知")){
            // 通过两个字典的映射获取对应的值，查询id随后进行赋值
            // city进行特殊处理
            if(key === 'exam_center_city'){
              this.setData({
                [`baoming_candidate_info.${value}`]: tools.findIdByName2(this.data[arrayFields[key]], dataFields[key])
              })
            }else{
              this.setData({
                [`baoming_candidate_info.${value}`]: tools.findIdByName(this.data[arrayFields[key]],dataFields[key])
              })
            }
        }else{
            console.log("通过name更新id时可能出错，请注意")
        }
      })
      // 加载志愿或专科专业选项
      await this.loadvvMajors()

      // 遍历专业字典，获取对应值并赋值id
      Object.entries(majorFields).forEach(([key,value]) =>{
        if(!dataFields[key].includes("未知")){
            // 通过两个字典的映射获取对应的值，查询id随后进行赋值
            this.setData({
                [`baoming_candidate_info.${value}`]: tools.findIdByName(this.data[arrayFields[key]],dataFields[key])
            })
        }else{
            console.log("通过name更新id时可能出错，请注意")
        }
    })
    // 更新下标
    this.updateIndexes(this.data.baoming_candidate_info)
  },
  // 录音功能区
  // 获取录音按键
  toggleRecording() {
    // const that = this;
    if (this.data.recording) {
        // 停止录音逻辑
        this.setData({ recording: false });
        const recorderManager = wx.getRecorderManager();
        recorderManager.stop();
        recorderManager.onStop((res) => {
            // 将录音文件临时路径存储到本地存储
            wx.setStorageSync('recordPath', res.tempFilePath);
            this.setData({ recordFilePath: res.tempFilePath });
            // 这里调用后端代码进行录音转文字
            // that.setData({ editableContent: '转换后的文本内容' });
            this.setData({ buttonText: '开始录音' });
        });
    } else {
        tools.checkRecordPermission().then(() => {
            // 开始录音逻辑
            this.setData({ recording: true });
            const recorderManager = wx.getRecorderManager();
            recorderManager.start({
                format: 'wav', // 设置为wav格式
                duration: 60000, 
                sampleRate: 44100, 
                numberOfChannels: 1, 
                encodeBitRate: 96000
            });
            this.setData({ buttonText: '停止录音' });
        }).catch((error) => {
            wx.showToast({
                title: 'error',
                icon:'none'
            });
        });
    }
  },

  // 上传录音并进行语音识别函数
  uploadAndRecognizeRecording() {
    if (!this.data.recordFilePath) {
        wx.showToast({ title: '请先录制录音', icon: 'none' });
        return;
    }
    const filePath = this.data.recordFilePath;
    // 调用后端识别接口
    http.asr(filePath).then(res =>{
      console.log("语音识别成功，文本如下：")
      console.log(res);
      // 根据返回的文本信息，提取其中的信息
      this.setData({ editableContent: res });
      // 调用后端的提取接口
      const postData = { "text": res };
      http.zsbExtract(postData).then(res =>{
        // 处理提取后的结果
        console.log("提取后的结果，如下：")
        console.log(res)
        // this.updateIdAndIndex(res.data.data)
        this.updateIdAndIndex(res.data)
      }).catch(err => {
        // 提取失败
        console.log('无法解析识别结果：', err);
        console.log('接收到的原始返回数据：', err.data);
      });
    }).catch(err =>{
      // 语音识别失败
      console.log('语音识别失败：', err);
      wx.showToast({ title: '录音识别失败', icon: 'none', duration: 2000 });
    })
  }
});